package com.niit.musicserve.controller;

import com.alibaba.fastjson.JSONObject;
import com.niit.musicserve.annotation.RequireRole;
import com.niit.musicserve.dao.ConsumerMapper;
import com.niit.musicserve.entity.Consumer;
import com.niit.musicserve.service.ConsumerService;
import com.niit.musicserve.utils.JwtUtil;
import com.niit.musicserve.utils.Md5Util;
import com.niit.musicserve.utils.Result;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/consumer")
public class ConsumerController {
	
	@Autowired
	private ConsumerService consumerService;
	@Autowired
	private JwtUtil jwtUtil;
	
	//注册用户方法
	@RequestMapping(value = "/register",method = RequestMethod.POST)
	public Result<String> regConsumer(@RequestBody Consumer  consumer){
		
		if(consumer.getConsumerEmail() ==  null){
			return Result.error("邮箱不能为空");
		}
		
		Consumer result = consumerService.consumerOfEmail(consumer.getConsumerEmail());
		if (result != null){
			return Result.error("邮箱已被注册");
		}
		
		
		//获取用户输入的密码
		String oldPassword = consumer.getConsumerPassword();
		//随即生成盐值
		String salt = UUID.randomUUID().toString().toUpperCase();
		//保存盐值
		consumer.setSalt(salt);
		//加密源密码，保存加密后的密码
		String newPassword = Md5Util.getMd5Password(oldPassword,salt);
		consumer.setConsumerPassword(newPassword);
		
		consumer.setCreateUser(consumer.getConsumerName());
		consumer.setUpdateUser(consumer.getConsumerName());
		
		Date date = new Date();
		consumer.setCreateTime(date);
		consumer.setUpdateTime(date);
		
		int regResult = consumerService.regConsumer(consumer);
		if (regResult > 0){
			
			return Result.success("注册成功",null);
		}else{
			
			return Result.error("注册失败");
		}
	}
	
	//删除用户方法
	@RequireRole({"admin"})
	@RequestMapping(value = "/deleteConsumer",method = RequestMethod.GET)
	public Result<String> deleteConsumer(HttpServletRequest request){
		
		String id = request.getParameter("consumerId");
		
		if(consumerService.deleteConsumer(Integer.parseInt(id))){
			
			return Result.success("删除成功",null);
		}else{
			
			return Result.error("删除失败");
		}
	}
	
	//更新用户信息方法
	@RequireRole({ "admin", "consumer" })
	@RequestMapping(value = "/updateConsumerInfo",method = RequestMethod.POST)
	public Result<String> updateConsumer(@RequestBody Consumer consumer) {
		
		try {
			
			if (consumer.getConsumerId() == null){
				return Result.error("用户ID不能为空");
			}
			
			consumer.setConsumerId(consumer.getConsumerId());
			consumer.setUpdateUser(consumer.getConsumerName());
			consumer.setUpdateTime(new Date());
			consumer.setConsumerSex(consumer.getConsumerSex());
			consumer.setConsumerLocation(consumer.getConsumerLocation());
			consumer.setConsumerSignature(consumer.getConsumerSignature());
			consumer.setConsumerEmail(consumer.getConsumerEmail());
			
			boolean result = consumerService.updateConsumer(consumer);
			if ( result){
				
				return Result.success("修改成功",null);
			}else {
				
				return Result.error("修改失败");
			}
		} catch (Exception  e) {
			e.printStackTrace();
			return Result.error("修改失败: " + e.getMessage());
		}
	}
	
	/**
	 * 更新用户头像
	 * @param file 头像文件
	 * @param request 请求
	 * @return 响应结果
	 */
	@RequestMapping(value = "/updateAvatar", method = RequestMethod.POST)
	public Result<String> updateAvatar(
		@RequestParam("file") MultipartFile file,
		HttpServletRequest request) {
		
		try {
			// 获取用户ID
			String consumerId = request.getParameter("id");
			if (consumerId == null || consumerId.trim().isEmpty()) {
				// 从token中获取用户ID
				String token = request.getHeader("Authorization");
				if (token != null && token.startsWith("Bearer ")) {
					token = token.substring(7);
					Claims claims = jwtUtil.getClaimsFromToken(token);
					if (claims != null) {
						String email = claims.getSubject();
						Consumer consumer = consumerService.consumerOfEmail(email);
						if (consumer != null) {
							consumerId = String.valueOf(consumer.getConsumerId());
						}
					}
				}
			}
			
			if (consumerId == null || consumerId.trim().isEmpty()) {
				return Result.error("用户ID不能为空");
			}
			
			if (file.isEmpty()) {
				return Result.error("文件不能为空");
			}
			
			// 生成文件名
			String fileName = System.currentTimeMillis() + file.getOriginalFilename();
			
			// 获取文件存储路径
			String filePath = System.getProperty("user.dir") + "/res/img/consumerPic";
			
			// 创建目录
			File fileDir = new File(filePath);
			if (!fileDir.exists()) {
				fileDir.mkdirs();
			}
			
			// 保存文件
			File dest = new File(filePath + System.getProperty("file.separator") + fileName);
			file.transferTo(dest);
			
			// 构造图片访问路径
			String picUrl = "/img/consumerPic/" + fileName;
			
			// 更新数据库
			Consumer consumer = new Consumer();
			consumer.setConsumerId(Integer.parseInt(consumerId));
			consumer.setConsumerAvatar(picUrl);
			
			boolean result = consumerService.updateConsumer(consumer);
			if (result) {
				return Result.success("头像更新成功", null);
			} else {
				return Result.error("头像更新失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("头像更新失败: " + e.getMessage());
		}
	}
	
	//查询所有用户方法
	@RequestMapping(value = "/allConsumer",method = RequestMethod.GET)
	public Result<List<Consumer>> allConsumer(HttpServletRequest request){
		
		return Result.success(consumerService.allConsumer());
	}
	
	//根据id查询用户方法
	@RequireRole({"admin","consumer"})
	@RequestMapping(value = "/consumerOfId",method = RequestMethod.GET)
	public Result<Consumer> consumerOfId(HttpServletRequest request){
		String id = request.getParameter("consumerId");
		
		return Result.success(consumerService.consumerOfId(Integer.parseInt(id)));
	}
	
	//根据名称查询用户方法
	@RequestMapping(value = "/consumerOfName",method = RequestMethod.GET)
	public Result<List<Consumer>> consumerOfName(HttpServletRequest request){
		
		return Result.success(consumerService.consumerOfName(request.getParameter("consumerName")));
	}
	
	//根据名称模糊查询用户方法
	@RequestMapping(value = "/consumerOfNameLike",method = RequestMethod.GET)
	public Result<List<Consumer>> consumerOfNameLike(HttpServletRequest request){
		
		return Result.success(consumerService.consumerOfLikeName(request.getParameter("consumerName")));
	}
	
	//用户登录方法
	@RequestMapping(value = "/login",method = RequestMethod.POST)
	public Result<JSONObject> login(
		@RequestBody(required = false) Consumer consumer,
		HttpServletRequest request){
		
		try {
			String email = null;
			String password = null;
			
			//参数校验
			if(consumer != null){
				email = consumer.getConsumerEmail();
				password = consumer.getConsumerPassword();
			}
			
			//如果通过以json格式传参或者request body参数为空
			if(email == null || email.trim().isEmpty() || password == null || password.trim().isEmpty()){
				email = request.getParameter("consumerEmail");
				password = request.getParameter("consumerPassword");
				
				StringBuilder sb = new StringBuilder();
				String line;
				try(BufferedReader reader = request.getReader()){
					while ((line = reader.readLine()) != null){
						sb.append(line);
					}
				}
				
				if(! sb.isEmpty()){
					JSONObject jsonParams = JSONObject.parseObject(sb.toString());
					if (email == null || email.trim().isEmpty()) {
						email = jsonParams.getString("consumerEmail");
					}
					if (password == null || password.trim().isEmpty()) {
						password = jsonParams.getString("consumerPassword");
					}
				}
			}
			
			if (email == null || email.trim().isEmpty() || password == null || password.trim().isEmpty()){
				return Result.error("邮箱或密码不能为空");
			}
			
			//获取对应邮箱的用户信息
			Consumer consumer1 = consumerService.consumerOfEmail(email);
			if (consumer1 == null){
				return Result.error("用户邮箱不存在");
			}
			
			//获取对应邮箱的用户密码做旧密码
			String oldPassword = consumer1.getConsumerPassword();
			//获取对应邮箱的用户盐值
			String salt = consumer1.getSalt();
			//加密用户输入的密码作为新密码
			String newPassword = Md5Util.getMd5Password(password,salt);
			//判断密码是否一致
			if (oldPassword.equals(newPassword)){
				//登录成功,生成JWT token
				String token = jwtUtil.generateToken(consumer1);
				
				//返回用户信息和token
				JSONObject userInfo = new JSONObject();
				
				userInfo.put("id",consumer1.getConsumerId());
				userInfo.put("username",consumer1.getConsumerName());
				userInfo.put("email",consumer1.getConsumerEmail());
				userInfo.put("token", token);
				
				return Result.successWithToken("登陆成功",token,userInfo);
			}else {
				return Result.error("登录失败，用户密码错误");
			}
		}
		catch (Exception e) {
			return Result.error("登录失败" + e.getMessage());
		}
	}

	//查询用户数量方法
	@RequestMapping(value = "/numberOfConsumer",method = RequestMethod.GET)
	public Result<Integer> numberOfConsumer(HttpServletRequest request){
		return Result.success(consumerService.numberOfConsumer());
	}
	
	//检查用户登录状态方法
	@RequestMapping(value = "/status", method = RequestMethod.GET)
	public Result<String> checkLoginStatus(HttpServletRequest request) {
		try {
			// 从请求头中获取token
			String token = request.getHeader("Authorization");
			if (token != null && token.startsWith("Bearer ")) {
				token = token.substring(7);
			}
			
			if (token == null || !jwtUtil.validateToken(token)) {
				return Result.error("未登录");
			}
			
			// 从token中解析用户信息
			Claims claims = jwtUtil.getClaimsFromToken(token);
			if (claims == null) {
				return Result.error("token无效");
			}
			
			return Result.success("已登录");
		} catch (Exception e) {
			return Result.error("验证失败: " + e.getMessage());
		}
	}
	
	//获取当前登录用户信息
	
	@RequestMapping(value = "/info", method = RequestMethod.GET)
	public Result<JSONObject> getUserInfo(HttpServletRequest request) {
		try {
			// 从请求头中获取token
			String token = request.getHeader("Authorization");
			if (token != null && token.startsWith("Bearer ")) {
				token = token.substring(7);
			}
			
			if (token == null || !jwtUtil.validateToken(token)) {
				return Result.error("无效的token");
			}
			
			// 从token中解析用户信息
			Claims claims = jwtUtil.getClaimsFromToken(token);
			if (claims == null) {
				return Result.error("无法解析token");
			}
			
			String email = claims.getSubject();
			Consumer consumer = consumerService.consumerOfEmail(email);
			if (consumer == null) {
				return Result.error("用户不存在");
			}
			
			// 构造返回的用户信息
			JSONObject userInfo = new JSONObject();
			userInfo.put("id", consumer.getConsumerId());
			userInfo.put("username", consumer.getConsumerName());
			userInfo.put("email", consumer.getConsumerEmail());
			userInfo.put("sex", consumer.getConsumerSex());
			userInfo.put("birth", consumer.getConsumerBirthday());
			userInfo.put("location", consumer.getConsumerLocation());
			userInfo.put("introduction", consumer.getConsumerSignature());
			userInfo.put("picUrl", consumer.getConsumerAvatar());
			
			return Result.success("获取用户信息成功", userInfo);
		} catch (Exception e) {
			return Result.error("获取用户信息失败: " + e.getMessage());
		}
	}
}
